package com.mirzabros.chexmo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;

import com.mirzabros.chexmo.service.Chexmo_Register_Service;
import com.mirzabros.chexmo.service.Chexmo_Reset_Service;
import com.mirzabros.chexmo.service.Chexmo_login_Service;
import com.mirzabros.chexmo.contant.Chexmo_Urls;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnSystemUiVisibilityChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import android.text.Html;
import android.text.method.LinkMovementMethod;

public class Chexmo_MainActivity extends ActionBarActivity {

	private AutoCompleteTextView spinnerAvailableID;
	private AutoCompleteTextView citizenship;
	private Calendar current;
	private long miliSeconds;
	private ArrayAdapter<String> idAdapter;
	private ArrayAdapter<String> adapterCountries;
	private SimpleDateFormat sdf;
	private Date resultdate;
	
	private String Actuallyselectedtimexone="";

	String[] idArray;
	
	String[] actArray;
	
	private static View systemUIView;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		/*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
		
		//PRIYAN - FULL  SCREEN
		
		 systemUIView = getWindow().getDecorView();
		 hideSystemUI();

		    if (android.os.Build.VERSION.SDK_INT >= 19) {
		        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(
		                new OnSystemUiVisibilityChangeListener() {
		                    @Override
		                    public void onSystemUiVisibilityChange(int visibility) {
		                        if (visibility == 0) {
		                            hideSystemUI();
		                        }
		                    }
		                });
		    }
		
		//PRIYAN - FULL SCREEN

		setContentView(R.layout.activity_main);
		
		idArray = TimeZone.getAvailableIDs();
		
		boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
		if (!tabletSize) {
			Toast toast = Toast.makeText(Chexmo_MainActivity.this, "Device Not Supported !!", Toast.LENGTH_LONG);
			toast.show();
			finish();
		} 
		
		if(!isOnline()){
			/*Toast toast = Toast.makeText(Chexmo_MainActivity.this, "Not Connected To The Internet !!", Toast.LENGTH_LONG);
			toast.show();*/
			Builder alert = new AlertDialog.Builder(Chexmo_MainActivity.this);
			alert.setTitle("No Internet Connection");
			alert.setMessage("Not Connected To The Internet");
			alert.setPositiveButton("OK",null);
			alert.show();
		}

		final Button btnLogin = (Button) findViewById(R.id.btnLogin);
		final Button btnForgot = (Button) findViewById(R.id.btnForgotpass);
		final Button btnregister = (Button) findViewById(R.id.btnRegister);

		final LinearLayout loginLay = (LinearLayout) findViewById(R.id.lay_login);
		final LinearLayout forgotLay = (LinearLayout) findViewById(R.id.lay_forgot_pass);
		final LinearLayout registerLay = (LinearLayout) findViewById(R.id.lay_register);
		
		TextView txtTerms = (TextView) findViewById(R.id.txt_terms);
		
		txtTerms.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Chexmo_MainActivity.this,Chexmo_TermsAndConditions_WebView.class);
				startActivity(intent);
			}
		});

		Button btnloginmain = (Button) findViewById(R.id.btnLoginform);
		btnloginmain.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Intent intent = new
				 * Intent(Chexmo_MainActivity.this,Chexmo_Webview.class);
				 * startActivity(intent);
				 */

				EditText txtUsername = (EditText) findViewById(R.id.txt_username);
				EditText txtPassword = (EditText) findViewById(R.id.txt_password);

				Chexmo_login_Service mps = new Chexmo_login_Service(
						Chexmo_MainActivity.this, txtUsername.getText()
								.toString(), txtPassword.getText().toString());
				// mps.execute(new String[] {
				// "http://mb.demoplease.com/xmlrpc-login-request" });
				mps.execute(new String[] { Chexmo_Urls.Login_Service });

				txtPassword.setText("");
				
			}
		});

		Button btnResetmain = (Button) findViewById(R.id.btn_reset);
		btnResetmain.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				EditText txtstorename = (EditText) findViewById(R.id.txt_storename);

				Chexmo_Reset_Service mps = new Chexmo_Reset_Service(
						Chexmo_MainActivity.this, txtstorename.getText()
								.toString());
				mps.execute(new String[] { Chexmo_Urls.Reset_Service });

			}
		});

		Button btnRegistermain = (Button) findViewById(R.id.btn_submit);
		btnRegistermain.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				EditText txtstorename = (EditText) findViewById(R.id.txt_storename_reg);
				EditText txtemail = (EditText) findViewById(R.id.txt_email);
				EditText txtpassword = (EditText) findViewById(R.id.txt_password_reg);
				EditText txtconpassword = (EditText) findViewById(R.id.txt_con_password);
				EditText txtpromocode = (EditText) findViewById(R.id.txt_promocode);
				EditText txtcode = (EditText) findViewById(R.id.txt_code);
				final AutoCompleteTextView txttimezone = (AutoCompleteTextView) findViewById(R.id.spinner_alltimezones);
				AutoCompleteTextView txtCountries = (AutoCompleteTextView) findViewById(R.id.spinner_allContries);
				EditText txtusd = (EditText) findViewById(R.id.txt_usd);

				CheckBox ChkAgree = (CheckBox) findViewById(R.id.acknowladge_check);
				
				

				
				/*txtTerms.setOnClickListener(new OnClickListener() {

			        @Override
			        public void onClick(View v) {
			        	Log.i("In Click", "In Click");
			        	Intent intent = new Intent(Chexmo_MainActivity.this,Chexmo_TermsAndConditions_WebView.class);
						startActivity(intent);
			        }
			    });*/

				if (ChkAgree.isChecked()
						&& txtconpassword.getText().toString()
								.equals(txtpassword.getText().toString())) {
					
					if(!isValidEmail(txtemail.getText())){
						Toast toast = Toast.makeText(Chexmo_MainActivity.this, "Email Not Valid !!", Toast.LENGTH_SHORT);
						toast.show();
						txtemail.requestFocus();
					}else if(txtstorename.getText().toString().equals("")){
						Toast toast = Toast.makeText(Chexmo_MainActivity.this, "Store Name Cannot Be Empty !!", Toast.LENGTH_SHORT);
						toast.show();
						txtstorename.requestFocus();
					}else if(txtpassword.getText().toString().equals("")){
						Toast toast = Toast.makeText(Chexmo_MainActivity.this, "Password Cannot Be Empty !!", Toast.LENGTH_SHORT);
						toast.show();
						txtpassword.requestFocus();
					}else if(txtusd.getText().toString().equals("")){
						Toast toast = Toast.makeText(Chexmo_MainActivity.this, "USD Cannot Be Empty !!", Toast.LENGTH_SHORT);
						toast.show();
						txtusd.requestFocus();
					}else{
						Chexmo_Register_Service mps = new Chexmo_Register_Service(
								Chexmo_MainActivity.this, txtstorename.getText()
										.toString(), txtemail.getText().toString(),
								txtpassword.getText().toString(), txtpromocode
										.getText().toString(), txtcode.getText()
										.toString(), Actuallyselectedtimexone, txtCountries.getText().toString()
										.toString(), txtusd.getText().toString());
						mps.execute(new String[] { Chexmo_Urls.Register_Service });
					}
					
					
				} else {
					if(!txtconpassword.getText().toString().equals(txtpassword.getText().toString())){
						Log.e("Passwords Doesn't Match", "Passwords Doesn't Match");
						Toast toast = Toast.makeText(Chexmo_MainActivity.this, "Passwords Doesn't Match", Toast.LENGTH_SHORT);
						toast.show();
						txtconpassword.requestFocus();
					}else{
						Log.e("Not Checked", "Not Checked");
						Toast toast = Toast.makeText(Chexmo_MainActivity.this, "Please Agree Our Terms", Toast.LENGTH_SHORT);
						toast.show();
						ChkAgree.requestFocus();
					}
					
				}
			}
		});

		loginLay.setVisibility(View.VISIBLE);
		forgotLay.setVisibility(View.GONE);
		registerLay.setVisibility(View.GONE);

		btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnLogin.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.pressed));
				btnForgot.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.not_pressed));
				btnregister.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.not_pressed));
				btnLogin.setTextColor(Color.parseColor("#0db796"));
				btnForgot.setTextColor(Color.parseColor("#000000"));
				btnregister.setTextColor(Color.parseColor("#000000"));
				loginLay.setVisibility(View.VISIBLE);
				forgotLay.setVisibility(View.GONE);
				registerLay.setVisibility(View.GONE);
			}
		});

		btnForgot.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnForgot.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.pressed));
				btnLogin.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.not_pressed));
				btnregister.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.not_pressed));
				btnLogin.setTextColor(Color.parseColor("#000000"));
				btnForgot.setTextColor(Color.parseColor("#0db796"));
				btnregister.setTextColor(Color.parseColor("#000000"));
				forgotLay.setVisibility(View.VISIBLE);
				loginLay.setVisibility(View.GONE);
				registerLay.setVisibility(View.GONE);
			}
		});

		btnregister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnregister.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.pressed));
				btnForgot.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.not_pressed));
				btnLogin.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.not_pressed));
				btnLogin.setTextColor(Color.parseColor("#000000"));
				btnForgot.setTextColor(Color.parseColor("#000000"));
				btnregister.setTextColor(Color.parseColor("#0db796"));
				registerLay.setVisibility(View.VISIBLE);
				forgotLay.setVisibility(View.GONE);
				loginLay.setVisibility(View.GONE);
			}
		});

		// PRIYAN: Populates Time Zone Spinner
		/*
		 * Spinner spnr_timezone = (Spinner)
		 * findViewById(R.id.spinner_alltimezones);
		 * 
		 * ArrayAdapter <CharSequence> adapter = new ArrayAdapter <CharSequence>
		 * (Chexmo_MainActivity.this, android.R.layout.simple_spinner_item );
		 * 
		 * adapter.setDropDownViewResource(android.R.layout.
		 * simple_spinner_dropdown_item); String[]TZ =
		 * TimeZone.getAvailableIDs(); ArrayList<String> TZ1 = new
		 * ArrayList<String>();
		 * 
		 * for(int i = 0; i < TZ.length; i++) {
		 * if(!(TZ1.contains(TimeZone.getTimeZone(TZ[i]).getDisplayName()))) {
		 * TZ1.add(TimeZone.getTimeZone(TZ[i]).getDisplayName()); } } for(int i
		 * = 0; i < TZ1.size(); i++) { adapter.add(TZ1.get(i)); }
		 * 
		 * spnr_timezone.setAdapter(adapter); for(int i = 0; i < TZ1.size();
		 * i++) { if(TZ1.get(i).equals(TimeZone.getDefault().getDisplayName()))
		 * { spnr_timezone.setSelection(i); } }
		 */
		// PRIYAN: Populates Time Zone Spinner

		// PRIYAN :Time Zone 2nd Version

		spinnerAvailableID = (AutoCompleteTextView) findViewById(R.id.spinner_alltimezones);
		citizenship = (AutoCompleteTextView) findViewById(R.id.spinner_allContries);
		

		sdf = new SimpleDateFormat("EEEE, dd MMMM yyyy HH:mm:ss");

		/*idAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, idArray);*/
		
		getGMTTime();

		fixTmeZone();
		
		

		// PRIYAN: Populates Contries Spinner

		// Locale[] locale = Locale.getAvailableLocales();
		String[] locale = Locale.getISOCountries();

		ArrayList<String> countries = new ArrayList<String>();
		
		final Map<String, String> countriesHash = new HashMap<String, String>();
		
		String country;
		String countryCode = null;
		for (String loc : locale) {

			Locale obj = new Locale("", loc);

			country = obj.getDisplayCountry();
			countryCode = obj.getCountry();
			if (country.length() > 0 && !countries.contains(country)) {
				countries.add(country);
				countriesHash.put(country, countryCode);
			}
		}

		/*
		 * ArrayList<String> countries = new ArrayList<String>(); String
		 * country; for( Locale loc : locale ){ country =
		 * loc.getDisplayCountry(); if( country.length() > 0 &&
		 * !countries.contains(country) ){ countries.add( country ); } }
		 */
		
		
		Collections.sort(countries, String.CASE_INSENSITIVE_ORDER);
		
		Collections.sort(countries, new Comparator<String>() {
	        @Override
	        public int compare(String s1, String s2) {
	            return s1.compareToIgnoreCase(s2);
	        }
	    });

		if(!citizenship.getText().toString().equals("")){
			Log.i("Country", citizenship.getText().toString());
			idArray = com.ibm.icu.util.TimeZone.getAvailableIDs(countriesHash.get(citizenship.getText().toString().trim()));
			fixTmeZone();
		}else{
			idArray = TimeZone.getAvailableIDs();
		}

		adapterCountries = new ArrayAdapter<String>(
				Chexmo_MainActivity.this, android.R.layout.simple_dropdown_item_1line,
				countries);
		citizenship.setAdapter(adapterCountries);
		
		final String finalcountryCode = countryCode;
		
		citizenship.setOnTouchListener(new View.OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				citizenship.selectAll();
				citizenship.showDropDown();
				
				if(!citizenship.getText().toString().equals("")){
					Log.d("In Touch", "real Touch");
					Log.d("finalcountryCode", finalcountryCode);
					Log.i("Country", citizenship.getText().toString());
					idArray = com.ibm.icu.util.TimeZone.getAvailableIDs(countriesHash.get(citizenship.getText().toString().trim()));
					fixTmeZone();
				}else{
					idArray = TimeZone.getAvailableIDs();
					fixTmeZone();
				}
				
				
				return false;
			}
			});

		citizenship.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String selection = adapterCountries.getItem(position).toString();
				
				Log.d("selection onClick", selection);
				
				if(!selection.equals("")){
					Log.d("In Touch", "In Touch");
					idArray = com.ibm.icu.util.TimeZone.getAvailableIDs(countriesHash.get(adapterCountries.getItem(position).toString().trim()));
					fixTmeZone();
				}else{
					idArray = TimeZone.getAvailableIDs();
					fixTmeZone();
				}
			}
		});
		
		//citizenship.setText((countries.size()==0)?"":countries.get(0));

		// PRIYAN: Populates Contries Spinner

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void getGMTTime() {
		current = Calendar.getInstance();

		miliSeconds = current.getTimeInMillis();

		TimeZone tzCurrent = current.getTimeZone();
		int offset = tzCurrent.getRawOffset();
		if (tzCurrent.inDaylightTime(new Date())) {
			offset = offset + tzCurrent.getDSTSavings();
		}

		miliSeconds = miliSeconds - offset;

		resultdate = new Date(miliSeconds);
		//System.out.println(sdf.format(resultdate));
	}
	
	public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
        return false;
        } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }  
	
	public boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
	

	public void hideSystemUI() {
	    systemUIView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
	        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
	        | View.SYSTEM_UI_FLAG_FULLSCREEN
	        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
	}
	
	private void fixTmeZone(){
		
		actArray = new String[idArray.length];
		
		for(int i=0;i<idArray.length;i++){
			
			//Log.e("idArray[i]", idArray[i]);
			
			String[] strthree = idArray[i].split("/");
			
			//Log.e("strthree", ""+strthree.length);
			
			String rexreate="";
			
			if(strthree.length>0){
				if(strthree.length==1){
					rexreate = strthree[0];
				}else if(strthree.length==2){
					rexreate = strthree[1];
				}else if(strthree.length==3){
					rexreate = strthree[1]+"/"+strthree[2];
				}
				//rexreate = ((strthree[1]==null)?strthree[0]:strthree[1])+((strthree[2]==null)?"":strthree[2]);
			}
			
			TimeZone timezone = TimeZone.getTimeZone(idArray[i]);
			
            String TimeZoneName = timezone.getDisplayName();

            int TimeZoneOffset = timezone.getRawOffset()
                    / (60 * 1000);

            int hrs = TimeZoneOffset / 60;
            int mins = TimeZoneOffset % 60;

            miliSeconds = miliSeconds + timezone.getRawOffset();

            resultdate = new Date(miliSeconds);

            actArray[i] = (rexreate + " : GMT " + hrs + "."+ mins);
            //actArray[i] = (TimeZoneName + " "+ sdf.format(resultdate) +" : GMT " + hrs + "."+ mins);
            //txtTimeZoneTime.setText("" + sdf.format(resultdate));
            miliSeconds = 0;
            
		}
		
		idAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, actArray);

		idAdapter
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinnerAvailableID.setAdapter(idAdapter);

		getGMTTime();

		spinnerAvailableID
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						
						Actuallyselectedtimexone = idArray[position];
						
						/*getGMTTime();
						String selectedId = (String) (parent
								.getItemAtPosition(position));

						TimeZone timezone = TimeZone.getTimeZone(selectedId);
						String TimeZoneName = timezone.getDisplayName();

						int TimeZoneOffset = timezone.getRawOffset()
								/ (60 * 1000);

						int hrs = TimeZoneOffset / 60;
						int mins = TimeZoneOffset % 60;

						miliSeconds = miliSeconds + timezone.getRawOffset();

						//resultdate = new Date(miliSeconds);
						//System.out.println(sdf.format(resultdate));

						miliSeconds = 0;*/
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});
		
		spinnerAvailableID.setOnTouchListener(new View.OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				spinnerAvailableID.selectAll();
				spinnerAvailableID.showDropDown();
				return false;
			}
			});
		
		//spinnerAvailableID.setText((actArray.length==0)?"":actArray[0]);

		// PRIYAN :Time Zone 2nd Version
	}

}
